<template>
  <div class="dialog-container">

    <el-row :gutter="10" class="mb8" v-if="!props.onlyShow">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dispatch:schedulingDailyTimetable:add']">增加班次</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dispatch:schedulingDailyTimetable:edit']">编辑</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dispatch:schedulingDailyTimetable:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" @click="updatePlaces"
          v-hasPermi="['dispatch:schedulingDailyTimetable:edit']">保存班次</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="schedulingDailyTimetableList" @selection-change="handleSelectionChange">
      <el-table-column fixed  type="selection" width="55" align="center" v-if="!props.onlyShow" />
      <el-table-column fixed  label="车辆" width="100" align="center" prop="plateNo" />
      <el-table-column fixed  label="驾驶员" align="center" prop="driverName" v-if="!props.onlyShow" />
      <el-table-column fixed  label="上日班次" width="100" align="center" prop="previousPlace" v-if="!props.onlyShow" />
      <el-table-column fixed  label="班次" width="100" align="center" prop="place" v-if="!props.onlyShow" >
        <template #default="scope">
          <el-input-number class="input-number"  size="small" v-model="scope.row.place" :min="0" controls-position="right"  />
        </template>
      </el-table-column>
      <template v-for="column_index in headerNums">
        <el-table-column width="60" :label="`时间${column_index}`" align="center">
          <template #default="scope">
            <span>{{ scope.row.timetableList[column_index - 1] ? scope.row.timetableList[column_index - 1].planTime : ''
            }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="`开往方向${column_index}`" width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.timetableList[column_index - 1]">{{ scope.row.timetableList[column_index - 1].routeName
            }}
              {{ scope.row.timetableList[column_index - 1].direction == 1 ? '上行' : '下行' }}>{{
                scope.row.timetableList[column_index -
                  1].endStation
              }}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <!-- 添加或修改排班明细对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="6"><el-button type="primary" plain icon="Plus" @click="add">增加时刻</el-button></el-col>
      </el-row>
      <el-form ref="schedulingDailyTimetableRef" :model="form" label-width="80px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车辆" prop="vehicleId">
              <el-select v-model="form.vehicleId" filterable placeholder="请选择线路">
                <el-option v-for="item in vehicleList" :key="item.id" :label="item.plateNo" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部位类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option v-for="dict in types" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上日班次" prop="previousPlace">
              <el-input v-model="form.previousPlace" placeholder="请输入上日班次" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当日班次" prop="place">
              <el-input :disabled="form.id ? true : false" v-model="form.place" placeholder="请输入当日班次" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-for="(item, index) in form.timetableList" :key="index">
          <el-col :span="8">
            <el-form-item label="时间" :prop="'timetableList.' + index + '.planTime'" :rules="rules.planTime">
              <el-time-picker v-model="item.planTime" format="HH:mm" value-format="HH:mm" @change="changeTimer" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="方向" :prop="'timetableList.' + index + '.routeAndDirection'" :rules="rules.planTime">
              <el-select v-model="item.routeAndDirection" placeholder="请选择">
                <el-option v-for="dict in selectList" :key="dict.routeId + '-' + dict.direction"
                  :label="dict.routeName + ' ' + (dict.direction == 1 ? '上行' : '下行') + '>' + dict.endStation"
                  :value="dict.routeId + '_' + dict.direction"></el-option>
              </el-select>
              <el-icon v-if="index>0"  @click="del(index)">
                <Close />
              </el-icon>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SchedulingDailyTimetable">
import { listSchedulingDailyTimetable, getSchedulingDailyTimetable, delSchedulingDailyTimetable, addSchedulingDailyTimetable, updateSchedulingDailyTimetable,editPlace } from "@/api/dispatch/schedulingDailyTimetable";
import {  getSelectListByPlace } from "@/api/dispatch/schedulingPlan";
import { getVehicleList } from "@/api/basic/vehicle";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const props = defineProps({
  // 当前的值
  schedulingId: [Number, String],
  planId: [Number, String],
  onlyShow:{
    type: Boolean,
    default: false
  }
});

const schedulingDailyTimetableList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref([]);
const places = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const headerNums = ref(0);
const data = reactive({
  form: {},
  queryParams: {
    schedulingId: ''
  },
  rules: {
    vehicleId: [
      { required: true, message: "车辆不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "请选择部位类型", trigger: "change" }
    ],
    previousPlace: [
      { required: true, message: "上日班次不能为空", trigger: "blur" }
    ],
    place: [
      { required: true, message: "当日班次不能为空", trigger: "blur" }
    ],
    planTime: [
      { required: true, message: "请选择时间", trigger: "change" }
    ],
    direction: [
      { required: true, message: "请选择方向", trigger: "change" }
    ]
  }
});
const types = ref([{ "label": "固定", "value": 1 }, { "label": "灵活", "value": 2 }]);
const { queryParams, form, rules } = toRefs(data);

/** 查询排班明细列表 */
function getList() {
  loading.value = true;
  listSchedulingDailyTimetable(queryParams.value).then(response => {
    schedulingDailyTimetableList.value = response.data;
    let nums = 0;
    response.data.forEach(element => {
      let length = element.timetableList.length
      nums = length > nums ? length : nums;
    });
    headerNums.value = nums
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  
  form.value = {
    "schedulingId": props.schedulingId,
    "previousPlace": 0,
    "place": schedulingDailyTimetableList.value.length+1,
    "type": 1,
    "deptId": null,
    "timetableList": [
      { "id": null, "routeId": null, "direction": null, "endStation": null, "planTime": "", "routeAndDirection": null }
    ]
  };
  proxy.resetForm("schedulingDailyTimetableRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  
  places.value = selection.map(item => item.place);
  let tempIds = [];
  selection.map(item => {
    item.timetableList.map(vo=>{
      tempIds.push(vo.id)
    })
  });
  ids.value = Array.from(new Set(tempIds))
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加班次";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || places.value
  getSchedulingDailyTimetable(props.schedulingId,_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改班次";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulingDailyTimetableRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      form.value.timetableList.forEach((element, index) => {
          let [routeId,direction] = element.routeAndDirection.split('_')
          form.value.timetableList[index].routeId = routeId
          form.value.timetableList[index].direction = direction
        });
      if (form.value.timetableList[0].id != null) {
        updateSchedulingDailyTimetable(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addSchedulingDailyTimetable(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除排班明细编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delSchedulingDailyTimetable(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

// 保存班次
function updatePlaces() {
  loading.value = true
  reset();
  let data = {
    schedulingId : props.schedulingId
  }
  let placeList = [];
  schedulingDailyTimetableList.value.forEach((element)=>{
    placeList.push({"vehicleId":element.vehicleId,"place":element.place})
  })
  data.placeList = placeList
  editPlace(data).then(response => {
    if(response.code != 200){
      proxy.$modal.msgError(response.msg);
    }
    proxy.$modal.msgSuccess("修改成功");
    loading.value = false;
    getList();
  });
}
const selectList = ref([])
function getDirectSelect(id) {
  getSelectListByPlace(id).then(res => {
    if (res.data.length) {
      selectList.value = res.data
    } else {
      selectList.value = []
    }
  })
}
function add() {
  let obj = {
    "id": null,
    "routeId": null,
    "direction": null,
    "endStation": null,
    "planTime": '',
    "routeAndDirection": null
  }
  form.value.timetableList.push(obj)
}
const vehicleList = ref([]);
function getVehicle() {
  getVehicleList().then(res => {
    vehicleList.value = res.rows
  })
}
getVehicle()
function del(e) {
  form.value.timetableList.splice(e, 1);
  // delete form.value.timetableList[e]
}
watch(props, (v) => {
  queryParams.value.schedulingId = v.schedulingId
  getList()
  getDirectSelect(v.planId)
}, { immediate: true });
</script>
<style scoped>
  .input-number{
    width:70px;
  }
</style>